package com.syswin.lhztest.nio.nio;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author:lhz
 * @date:2018/12/12 15:23
 */
public class NIOServer {

	public static void main(String[] args) throws Exception {

		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false); //设置阻塞模式
		serverSocketChannel.socket().bind(new InetSocketAddress(8080));
		System.out.println("启动成功");
		while(true){
			SocketChannel socketChannel = serverSocketChannel.accept();
			//top请求 读取/响应
			if(socketChannel !=null){
				System.out.println("收到新连接:"+socketChannel.getRemoteAddress());
				socketChannel.configureBlocking(false);//默认是阻塞，一定要设置为非阻塞
				try{
					ByteBuffer requestBuffer = ByteBuffer.allocate(1024);
					while (socketChannel.isOpen() && socketChannel.read(requestBuffer) !=-1){
						//长连接情况下，需要手动判断数据有没有读取结束（此处做一个简单的判断，超过0字节就认为请求结束）
						if(requestBuffer.position()>0) break;
					}
					if(requestBuffer.position() == 0) continue;
					requestBuffer.flip();
					byte[] content = new byte[requestBuffer.limit()];
					requestBuffer.flip();
					System.out.println(new String(content));
				}catch (Exception e){

				}

			}
		}
	}
}
